#pragma once
#include <cstring>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
namespace Client
{
    class UdpClient
    {
    public:
        UdpClient(const std::string &serverip, const uint16_t &serverport)
            : _serverip(serverip), _serverport(serverport), _sockfd(-1), _quit(false)
        {
        }
        void initClient()
        {
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                std::cerr << "socket error : " << errno << " : " << strerror(errno) << std::endl;
                exit(2);
            }
            std::cout << "socket success : " << _sockfd << std::endl;
        }
        void run()
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            server.sin_port = htons(_serverport);
            std::string message;
            char cmdline[1024];
            while (!_quit)
            {
                std::cout << "[XXX@我的远程机器 udp]# ";
                fgets(cmdline, sizeof(cmdline), stdin);
                message = cmdline;
                sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
                char message[1024];
                struct sockaddr_in client;
                socklen_t len = sizeof(client);
                ssize_t s = recvfrom(_sockfd, message, sizeof(message) - 1, 0, (struct sockaddr *)&server, &len);
                if (s > 0)
                {
                    message[s] = 0;
                    std::cout << message << std::endl;
                }
            }
        }
        ~UdpClient()
        {
        }

    private:
        int _sockfd;
        std::string _serverip;
        uint16_t _serverport;
        bool _quit;
    };
}